package com.cskaoyan.datasource;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.util.LinkedList;

/**
 * 创建日期: 2022/10/10 14:59
 *
 * @author ciggar
 *
 * 自动扩容
 */
public class MyConnectionPoolV2 {

    // 定义一个容器，这个容器中存放的是多个连接对象
    // 从头部去取，从尾部去添加
    static LinkedList<Connection> pool;

    static int INIT_SIZE = 10;
    static int MIN_SIZE = 2;
    static int INCREMENT = 5;


    // 初始化数据库连接池
    static {

        pool = new LinkedList<>();

        addCapcity(INIT_SIZE);


    }


    // 获取连接
    public static Connection getConnection() {

        // 自动扩容
        if (pool.size() < MIN_SIZE) {
            addCapcity(INCREMENT);
        }

        Connection connection = pool.removeFirst();

        return connection;

    }


    // 返回连接
    public static void returnConnection(Connection connection){

        pool.addLast(connection);

    }


    // 扩容的方法
    private static void addCapcity(int num) {

        for (int i = 0; i < num; i++) {
            Connection connection = JDBCUtils.getNewConnection();
            pool.addLast(connection);
        }

    }

}
